from PyQt5.QtWidgets import QHBoxLayout, QLabel, QComboBox
from PyQt5.QtCore import pyqtSignal

class TypeSelector(QHBoxLayout):
    types_loaded = pyqtSignal(list)
    
    def __init__(self, api_client):
        super().__init__()
        self.api_client = api_client
        self.video_types = []
        self.setup_ui()
        self.load_video_types()
        
    def setup_ui(self):
        self.lbl_type = QLabel("视频类型:")
        self.cmb_type = QComboBox()
        self.cmb_type.setPlaceholderText("加载中...")
        self.cmb_type.setEnabled(False)
        
        self.addWidget(self.lbl_type)
        self.addWidget(self.cmb_type)
        self.addStretch()
        
        # 连接信号
        self.types_loaded.connect(self.populate_combo)
    
    def load_video_types(self):
        """从后端加载视频类型数据"""
        try:
            types = self.api_client.get_video_types()
            self.types_loaded.emit(types)
        except Exception as e:
            self.cmb_type.setPlaceholderText("加载失败")
            print(f"加载视频类型失败: {str(e)}")
    
    def populate_combo(self, types):
        """填充类型下拉框"""
        self.video_types = types
        self.cmb_type.clear()
        
        if not types:
            self.cmb_type.setPlaceholderText("无可用类型")
            return
            
        self.cmb_type.addItem("--请选择类型--", None)
        for type_data in types:
            self.cmb_type.addItem(type_data['name'], type_data['id'])
        
        self.cmb_type.setEnabled(True)
        self.cmb_type.setPlaceholderText("")
    
    def get_selected_type(self):
        """获取当前选择的类型"""
        current_index = self.cmb_type.currentIndex()
        if current_index <= 0:  # 第一个是"请选择"项
            return None
        return self.video_types[current_index - 1]